const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koajwt = require('koa-jwt')
const cors = require('@koa/cors');
import ApiRouter from './routes/index';
import { SwaggerRouter } from 'koa-swagger-decorator'
const config  = require("./config.js")
const router = new SwaggerRouter();

router.use('/api', ApiRouter.routes());

app.use(cors());
 
// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
// app.use(async (ctx, next) => {
//   return next().catch((err) => {
//     if(err.status === 401){
//       ctx.status = 401;
//       ctx.body = {
//         code: '-2000',
//         desc: '登陆过期，请重新登陆'
//       };
//     }else{
//       throw err;
//     }
//   })
// })

app.use(koajwt({
  secret: config.secretKey,
  passthrough:true
}).unless({
  path: [/^\/api\/user\/regist/,/^\/api\/user\/login/,/^\/api\/swagger-html/,/^\/api\/swagger-json/]
}))
// routes
app.use(router.routes(), router.allowedMethods())
 
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
